﻿Namespace ErrorHandling

    Module mError

        Sub UnhandledErrorHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)

            'Handles any error not handled by a Try Catch statement

            Dim FS As System.IO.FileStream = New System.IO.FileStream(Globals.sRootPath & "\error.txt", System.IO.FileMode.OpenOrCreate)
            Dim BW As System.IO.BinaryWriter = New System.IO.BinaryWriter(FS)

            BW.Write(vbCrLf & vbCrLf & "[============================================================================================================]" & vbCrLf & vbCrLf)

            BW.Write("==[ " & DateTime.Now.ToString & " ]==" & vbCrLf & vbCrLf)
            BW.Write("Error Message: " & args.ExceptionObject.Message & vbCrLf & vbCrLf)
            BW.Write("Source: " & args.ExceptionObject.Source & vbCrLf)
            BW.Write("Target Site: " & args.ExceptionObject.TargetSite.Name & vbCrLf)
            BW.Write("Stack trace follows... " & vbCrLf & args.ExceptionObject.StackTrace & vbCrLf)

            BW.Write(vbCrLf & vbCrLf & "[============================================================================================================]" & vbCrLf & vbCrLf)

            BW.Flush()
            BW.Close()

            MsgBox(CType(args.ExceptionObject, Exception).Source & vbCrLf & vbCrLf & CType(args.ExceptionObject, Exception).Message, MsgBoxStyle.OkOnly And MsgBoxStyle.Critical)

            Application.Exit()
            End

        End Sub

    End Module

End Namespace